import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:xiandou/Common.dart';
import 'package:xiandou/Request/DioManager.dart';
import 'package:xiandou/Request/NWApi.dart';
import 'package:xiandou/Request/NWMethod.dart';
import 'package:xiandou/Views/XDWebViewController.dart';
import 'package:xiandou/common/Global.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:xiandou/home/TaskDetailView.dart';
import 'package:xiandou/common/GlobalEventBus.dart';
import 'package:xiandou/login/Login.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';



class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true;

  List _taskListData =[];       // 任务列表
  List _categoryData =[];       //分类数据
  List _bannerListData = [];    // banner数据
  int selectedTaskId = 0;       // 选中任务id
  int _selectCategoryIndex = 0; //分类索引
  String _categoryId = '0';     // 分类id
  int _page = 1;               // 分页页码
  ScrollController _scrollController = new ScrollController();

  @override
  void initState (){
    super.initState();
    _loadBannerData();
    _loadCategorieListData();
    _loadTaskListData(true);
//    _scrollController.addListener(() {
//      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
//        _onLoadmore();
//      }
//    });
    GlobalEventBus().event.on<AuthorizationChangeEvent>().listen((event) {
      if(event.isLogin == false){
        Navigator.pushReplacement(
            context, new MaterialPageRoute(builder: (context) => LoginPage()));
      }
    });
  }

  Future<dynamic> _onLoadmore() {
    _page++;
    _loadTaskListData(false);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  _loadBannerData() async {
    DioManager().request(NWMethod.GET, NWApi.getBannerApi,params: null,success: (data){
      print(NWApi.getBannerApi+Global.profile.token+'6666');
      print(data);
      setState(() {
        _bannerListData =data;
      });
    },
    error: (error){
      Fluttertoast.showToast(msg: error.message);
    });
  }

  _loadCategorieListData() async {
    DioManager().request(NWMethod.GET, NWApi.getCategorieListsApi,params: null,success: (data){
      print(data);
      setState(() {
        _categoryData = data;
      });
    }, error: (error){
      Fluttertoast.showToast(msg: error.message);
    });
  }

  _loadTaskListData(bool isRefresh) async {
    if(isRefresh){
      _page = 1;
      _taskListData.clear();
    }
    var params ={"categoryId":_categoryId,"page":_page.toString(),"pageSize":"20"};
    DioManager().request(NWMethod.GET, NWApi.getTaskListApi,params: params,success: (data){
      print(data.toString()+'333');
      setState(() {
        if(isRefresh == true) {
          _taskListData = data;
        }else {
          _taskListData.addAll(data);
        }
      });
    }, error: (error){
      Fluttertoast.showToast(msg: error.message);
    });
  }

  Future<Null> _refresh() async {
    _page = 1;
    _taskListData.clear();
    await _loadTaskListData(true);
    return;
  }

  Widget build(BuildContext context) {
    Widget categotyWidget(String label,int index) {
      return new GestureDetector(
        onTap:()  {
          _page =1;
          _selectCategoryIndex =index;
          _categoryId = _categoryData[index]['categoryId'].toString();
          _loadTaskListData(true);
          setState(() {

          });
        },
        child: Container(
          width: MediaQuery.of(context).size.width / 3.5,
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Text(_categoryData[index]['categoryName'],style: TextStyle(fontSize: 14,color: Color(0xff333333))),
                  )
              ),
              Offstage(
                offstage: _selectCategoryIndex == index ? false : true,
                child: Container(
                  height: 2,
                  width: 27.5,
                  margin: const EdgeInsets.only(bottom: 8),
                  decoration: new BoxDecoration(
                    color: Color(0xffFF5236),
                  ),
                )
              )
            ],
          ),
        )
      );
    }

    return Scaffold(
      appBar: CupertinoNavigationBar(
        backgroundColor: Colors.white,
        middle: const Text('首页'),
        transitionBetweenRoutes:false,
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            Container(
              height: 200,
              padding: const EdgeInsets.all(10),
//              decoration: new BoxDecoration(
//                borderRadius: BorderRadius.all(
//                  Radius.circular(20.0),
//                ),
//              ),
              child: Swiper(
                itemCount: _bannerListData.length,
                autoplay: _bannerListData.isNotEmpty,
                itemBuilder: (BuildContext context,int index) {
                  String url = _bannerListData[index]['cover'];
                  String title = _bannerListData[index]['title'];
                  return GestureDetector(
                    onTap: () {
                      Navigator.push(
                        context,
                        new MaterialPageRoute(builder: (context) => new XDWebViewController(title: title,url: url,)),
                      );
                    },
                    child: ClipRRect(
                        borderRadius: BorderRadius.circular(4),
                        child: Image.network(
                          url,fit: BoxFit.cover,
                        )
                    )
                  );
                },
                pagination: SwiperPagination(),
              ),
            ),
            Container(
                height: 44,
              decoration: new BoxDecoration(
//                color: Colors.green,
              ),
                child: ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemCount: _categoryData.length,
                  itemBuilder: (BuildContext context, int index) =>categotyWidget(_categoryData[index]['categoryName'], index),
                ),
            ),
            SizedBox(
              height: 6,
              child: Container(
                decoration: new BoxDecoration(
                  color: Color(0xffF6F6F6),
                ),
              ),
            ),
            Expanded(
              child:Container(
                child: EasyRefresh(
                  child: ListView.builder(itemBuilder: (BuildContext context,int index){
                    if(_taskListData.length == 0) {
                      return Container(
                        padding: const EdgeInsets.only(top: 50),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image(image: AssetImage('assets/d_empty.png'),width: 200,height: 200,),
                            SizedBox(height: 30,),
                            Text('暂无内容',style: TextStyle(color: Common.darkColor,fontSize: 14),),
                          ],
                        ),
                      );
                    }
                    return GestureDetector(
                        onTap: (){
                          selectedTaskId = _taskListData[index]['taskId'];
                          Navigator.push(
                            context,
                            new MaterialPageRoute(builder: (context) => new TaskDetailPage(taskId:selectedTaskId)),
                          );
                        },
                        child:Container(
//                          height: 54,
                          padding: const EdgeInsets.fromLTRB(15, 15, 15, 10),
                          child: Row(
                            children: <Widget>[
                              new Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      _taskListData[index]['taskTitle'],
                                      style: TextStyle(fontSize: 16,fontFamily: 'PingFang-SC-Bold',fontWeight: FontWeight.bold,),
                                    ),
                                    Padding(
                                        padding: const EdgeInsets.only(top: 5),
                                        child: Text(
                                          '截止时间'+_taskListData[index]['endTime'],
                                          style: TextStyle(color: Color(0xff666666),fontSize: 13),
                                        )
                                    ),
                                  ],
                                ),
                              ),
                              Container(
                                margin: const EdgeInsets.only(right: 15),
                                child: Container(
                                  width: 60,
//                                  alignment: Alignment.centerRight,
                                  child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.end,
//                                    textBaseline: TextBaseline.alphabetic,
                                    children: <Widget>[
                                      new Image.asset('assets/xiandou.png',width: 24,height: 24,),
                                      SizedBox(width: 3,),
                                      Text(_taskListData[index]['award'].toString(),style: (TextStyle(color: Color(0xffFFBD18),fontWeight: FontWeight.bold,fontSize: 17)),)
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        )
                    );
                  }, itemCount: _taskListData.length == 0 ? 1 : _taskListData.length,controller: _scrollController,),
                  onRefresh: () async{
                    _refresh();
                  },
                  onLoad: () async{
                    _onLoadmore();
                  },
                  bottomBouncing: true,
                ),
              )
            )
          ],
        ),
      )
    );
  }
}

